<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告提示框 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>

      <!-- 选择商品分类下拉框 -->
      <div class="downForm">
        <el-form :model="ruleForm" ref="ruleForm" label-width="120px" status-icon>
          <el-form-item label="选择商品分类：">
            <el-cascader
              expand-trigger="hover"
              :options="prent"
              :props="cascader"
              v-model="ballModel"
              @change="handleChange"
              change-on-select
            ></el-cascader>
          </el-form-item>
        </el-form>
      </div>

      <!-- tab切换 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <div class="paaramsTab">
            <!-- 添加参数按钮 -->
            <el-button type="primary" size="mini" :disabled="isButab" @click="Modifys = true">添加参数</el-button>
            <!-- 动态参数表格区域 -->
            <el-table :data="paramsList" border stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 循环渲染Tag标签 -->
                  <el-tag
                    v-for="(item, key) in scope.row.attr_vals"
                    :key="key"
                    closable
                    @close="handleClose(key, scope.row)"
                  >{{item}}</el-tag>
                  <!-- 输入的文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <!-- 添加按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="butPrim(scope.row)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeDele(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <div class="attributeTab">
            <!-- 添加属性按钮 -->
            <el-button type="primary" size="mini" :disabled="isButab" @click="Modifys = true">添加属性</el-button>
            <!-- 添加静态属性表格区域 -->
            <el-table :data="attributeList" border stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 循环渲染Tag标签 -->
                  <el-tag
                    v-for="(item, key) in scope.row.attr_vals"
                    :key="key"
                    closable
                    @close="handleClose(key, scope.row)"
                  >{{item}}</el-tag>
                  <!-- 输入的文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <!-- 添加按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数属性" prop="attr_name"></el-table-column>
              <el-table-column label="操作" prop="username">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="butPrims(scope.row)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeDeles(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 编辑动态参数对话框 -->
    <el-dialog
      title="修改动态参数"
      :visible.sync="dialogModify"
      width="50%"
      @close="modifyClose"
      :lock-scroll="false"
    >
      <!-- 内容主体区域 -->
      <el-form :model="rolesModify" :rules="rules" ref="rolesModify" label-width="80px" status-icon>
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="rolesModify.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!--  底部按钮区域 -->
      <span slot="footer">
        <el-button @click="dialogModify = false">取 消</el-button>
        <el-button type="primary" @click="butdialog('rolesModify')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑静态属性对话框 -->
    <el-dialog
      title="修改静态属性"
      :visible.sync="dialogModifys"
      width="50%"
      @close="modifyCloses"
      :lock-scroll="false"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="rolesModifys"
        :rules="rules"
        ref="rolesModifys"
        label-width="80px"
        status-icon
      >
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="rolesModifys.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!--  底部按钮区域 -->
      <span slot="footer">
        <el-button @click="dialogModifys = false">取 消</el-button>
        <el-button type="primary" @click="butdialogs('rolesModifys')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 添加分类对话框 -->
    <el-dialog
      :title="titleList"
      :visible.sync="Modifys"
      width="50%"
      @close="titleClose"
      :lock-scroll="false"
    >
      <!-- 内容主体区域 -->
      <el-form :model="listModify" :rules="rules" ref="listModify" label-width="80px" status-icon>
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="listModify.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!--  底部按钮区域 -->
      <span slot="footer">
        <el-button @click="Modifys = false">取 消</el-button>
        <el-button type="primary" @click="ballTitle('listModify')">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
s
<script>
export default {
  data() {
    return {
      // 表单的验证规则
      rules: {
        // 验证用户名是否合法
        attr_name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ]
      },
      // 添加分类按钮里表单的数据
      ruleForm: {
        cat_name: "", // 将要添加的分类的名称
        cat_pid: 0, // 父级分类的Id
        cat_level: 0 // 分类的等级，默认要添加的是1级分类
      },
      // 点击分类按钮下拉框数据
      prent: [],
      // 指定级联选择器的配置对象
      cascader: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 选中的父级分类的ID值数组
      ballModel: [],
      // tab切换页数据绑定
      activeName: "many",
      // 动态参数表格数据
      paramsList: [],
      // 静态属性表格数据
      attributeList: [],
      // 控制动态参数编辑按钮对话框隐藏与显示
      dialogModify: false,
      // 编辑动态参数对话框用户信息数据
      rolesModify: {},
      // 控制静态属性编辑按钮对话框隐藏与显示
      dialogModifys: false,
      // 编辑静态属性对话框用户信息数据
      rolesModifys: {},
      // 控制添加分类对话框隐藏与显示
      Modifys: false,
      // 添加分类对话框数据
      listModify: {}
    };
  },
  methods: {
    // 添加分类按钮获取分类列表数据
    async butCate() {
      const result = await this.$http.get("categories/");
      if (result.meta.status == 200) {
        this.prent = result.data;
        console.log(this.prent);
      }
      this.dialogVisible = !this.dialogVisible;
    },
    // 下拉框选项发生变化触发这个事件
    async handleChange() {
      if (this.ballModel.length !== 3) {
        this.ballModel = [];
        this.paramsList = [];
        this.attributeList = [];
        this.$message.error("只允许为第三级分类设置相关参数！");
      }
      this.getList();
    },
    // tab切换时会触发这个事件
    handleClick() {
      console.log(this.activeName);
      this.getList();
    },
    async getList() {
      const result = await this.$http.get(
        `categories/${this.isId}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (result.meta.status == 200) {
        result.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          item.inputVisible = false;
          item.inputValue = "";
        });
        this.paramsList = result.data;
        console.log(result.data);
        this.attributeList = result.data;
      } else {
        this.$message.error("获取数据失败！");
      }
    },
    // 动态删除按钮事件
    async removeDele(id) {
      // 弹框询问用户是否删除数据;
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          lockScroll: false
        }
      ).catch(err => err);
      console.log(res);
      console.log(id);
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (res == "cancel") {
        this.$message.warning("您已取消删除操作！");
      } else {
        const reslut = await this.$http.delete(
          `categories/${id.cat_id}/attributes/${id.attr_id}`
        );
        if (reslut.meta.status == 200) {
          this.getList();
          this.$message.success("您已删除该数据！");
        } else {
          this.$message.error("删除失败！");
        }
      }
    },
    // 静态删除按钮事件
    async removeDeles(id) {
      // 弹框询问用户是否删除数据;
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          lockScroll: false
        }
      ).catch(err => err);
      console.log(res);
      console.log(id);
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (res == "cancel") {
        this.$message.warning("您已取消删除操作！");
      } else {
        const reslut = await this.$http.delete(
          `categories/${id.cat_id}/attributes/${id.attr_id}`
        );
        if (reslut.meta.status == 200) {
          this.getList();
          this.$message.success("您已删除该数据！");
        } else {
          this.$message.error("删除失败！");
        }
      }
    },
    // 监听动态参数编辑对话框事件，当关闭对话框会触发事件
    modifyClose() {
      // 当修改对话框关闭时会触发表单重置事件
      this.$refs.rolesModify.resetFields();
    },
    // 监听静态属性编辑对话框事件，当关闭对话框会触发事件
    modifyCloses() {
      // 当修改对话框关闭时会触发表单重置事件
      this.$refs.rolesModifys.resetFields();
    },
    // 点击动态参数编辑按钮事件
    butPrim(id) {
      this.rolesModify = id;
      this.dialogModify = !this.dialogModify;
    },
    // 提交动态参数确定按钮接口
    butdialog(rolesModify) {
      this.$refs[rolesModify].validate(async valid => {
        if (valid) {
          const reslut = await this.$http.put(
            `categories/${this.rolesModify.cat_id}/attributes/${this.rolesModify.attr_id}`,
            { attr_name: this.rolesModify.attr_name, attr_sel: this.activeName }
          );
          if (reslut.meta.status == 200) {
            this.getList();
            this.dialogModify = !this.dialogModify;
            this.$message.success("修改动态参数成功！");
          } else {
            this.$message.error("修改动态参数失败！");
          }
        }
      });
    },
    // 提交静态属性确定按钮接口
    butdialogs(rolesModifys) {
      this.$refs[rolesModifys].validate(async valid => {
        if (valid) {
          const reslut = await this.$http.put(
            `categories/${this.rolesModifys.cat_id}/attributes/${this.rolesModifys.attr_id}`,
            {
              attr_name: this.rolesModifys.attr_name,
              attr_sel: this.activeName
            }
          );
          if (reslut.meta.status == 200) {
            this.getList();
            this.dialogModifys = !this.dialogModifys;
            this.$message.success("修改静态参数成功！");
          } else {
            this.$message.error("修改静态参数失败！");
          }
        }
      });
    },
    // 点击静态属性编辑按钮事件
    butPrims(id) {
      this.rolesModifys = id;
      this.dialogModifys = !this.dialogModify;
    },
    // 监听添加分类对话框事件，当关闭对话框会触发事件
    titleClose() {
      // 当修改对话框关闭时会触发表单重置事件
      this.$refs.listModify.resetFields();
    },
    // 提交添加分类接口
    ballTitle(listModify) {
      this.$refs[listModify].validate(async valid => {
        if (valid) {
          // 验证通过发起网络接口请求
          const result = await this.$http.post(
            `categories/${this.isId}/attributes`,
            { attr_name: this.listModify.attr_name, attr_sel: this.activeName }
          );
          if (result.meta.status == 201) {
            this.getList();
            this.Modifys = !this.Modifys;
            this.$message.success("添加动态参数成功！");
          } else {
            this.$message.error("添加动态参数失败！");
          }
        } else {
          this.$message.error("用户创建失败！");
        }
      });
    },
    // 分类参数删除事件
    async handleClose(key, val) {
      val.attr_vals.splice(key, 1);
      this.setPut(val);
    },
    // 文本框失去焦点或者按下了Enter键
    async handleInputConfirm(val) {
      if (val.inputValue.trim()) {
        val.attr_vals.push(val.inputValue.trim());
        this.setPut(val);
      }
      val.inputValue = "";
      val.inputVisible = false;
    },
    // 发起网络请求，提交参数到后台数据库
    async setPut(val) {
      const reslut = await this.$http.put(
        `categories/${this.isId}/attributes/${val.attr_id}`,
        {
          attr_name: val.attr_name,
          attr_sel: this.activeName,
          attr_vals: val.attr_vals.join(",")
        }
      );
      if (reslut.meta.status == 200) {
        this.$message.success("操作成功！");
      } else {
        this.$message.error("添加参数失败！");
      }
    },
    // 点击按钮，展示输入文本框
    showInput(val) {
      val.inputVisible = true;
      // 让文本框自动获取焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会执行回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
        console.log(_);
      });
    }
  },
  created() {
    this.butCate();
  },
  // 计算属性
  computed: {
    // 判断下拉框里面的值是不是3级分类，如果不是就返回true
    isButab() {
      if (this.ballModel.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    // 判断下拉框里面的值是不是3级分类，如果是就获取ID值
    isId() {
      if (this.ballModel.length == 3) {
        return this.ballModel[2];
      } else {
        return null;
      }
    },
    // 动态计算出添加分类的标题
    titleList() {
      if (this.activeName == "many") {
        return "添加动态参数";
      } else {
        return "添加静态属性";
      }
    }
  }
};
</script>

<style lang="stylus" scoped>
.downForm {
  margin-top: 16px;
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 100px;
}
</style>
